package com.gxa.ehome.controller;

import com.gxa.ehome.util.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;


@Controller
@ResponseBody
public class UploadController {

    //@RequestMapping(value = "/upload",method = RequestMethod.POST)
    //通过MultipartFile对象接收前端传递的图像数据,基于layui只能用
    //file获取目标参数名(默认,不能修改).
    // HttpServletRequest 为了获取上下文对象,从而获取"/"
    @PostMapping(value ="/upload")
    public Map <String, Object> upload(@RequestParam("file") MultipartFile multipartFile,
                                       HttpServletRequest request) throws IOException {
        //
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println("originalFilename" +originalFilename);
        //从原始文件名中获得后缀,作为新添加文件的文件名后缀(匹配)
        String subfix=originalFilename.substring(originalFilename.indexOf(".")+1);
        System.out.println("subfix"+subfix);
        //使用UUID作为文件名,保证服务器中存放的文件名字唯一
        String targetFile=UUID.randomUUID().toString().replace("-","")+","+subfix;
        System.out.println(targetFile);

        //通过request获取对当前程序的根路径
        String path=request.getServletContext().getRealPath("/");
        String fileName=path+"static/uploadImg/"+targetFile;
        System.out.println("Filename:"+fileName);
        //构建文件对象
        File uploadFile=new File(fileName);
        //核心操作:
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            //e.printStackTrace();
            throw e;
        }
        MapUtil mapUtil=new MapUtil();
        //返回状态0 表示上传成功
        mapUtil.setCode("0");
        mapUtil.put("fileName",targetFile);
       return mapUtil.getValues();

    }




}
